var pinyin = require("pinyin2");
var multiparty = require('multiparty');
var util = require('util');
var uuid = require('node-uuid');
var fs = require('node-fs');
var gm = require('gm');
var http = require('http');
var mkdirp = require('mkdirp');
var cryptojs = require('cryptojs').Crypto;

var setting = require('./setting');
var resultJson = require('./result-json');
var Consts = require("./consts");

var iconv = require('iconv-lite');


var JPush = require("./lib/JPush/JPush");
//var client = JPush.buildClient('65711314cee4039eaf25f414','989bb2a4dae83f27c8f7e8bd');
var client = JPush.buildClient('95017e38171d46f255433a23','f349d5f8b1e470356f6e8d49');
var Utils = {
    msgIdArray: new Array(),
    pushMessage: function(obj){

        var platform = obj.platform;
        var alias = obj.alias;
        var alertmsg = obj.alertmsg;
        var alerttitle = obj.alerttitle;
        var contentmsg = obj.contentmsg;
        var option = obj.option;
        if(!platform || !alias || !alertmsg ){
            console.log("platform: " + platform + "\talias:" + alias + "\talertmsg:" + alertmsg);
            return;
        }

        var fromUser = option.extra;
        var msgContent = JSON.stringify(fromUser);
        var fUsername = fromUser.username;
        var msgIdArray = Utils.msgIdArray;

        var overrideMsgId = msgIdArray[alias];
        if(!overrideMsgId) overrideMsgId = null;
        else overrideMsgId = parseInt(overrideMsgId);


        console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>overrideMsgId: ' + overrideMsgId);


        client.push().setPlatform(JPush.ALL)
        .setAudience(JPush.tag(alias))
        .setNotification('ec', JPush.ios(alertmsg, 'default', 5, true, null), JPush.android(alertmsg, alerttitle, 5, option))
        .setMessage(msgContent)
        .setOptions(null, 60, overrideMsgId, true) // 默认为开发环境(false)
        .send(function(err, res) {
            if (err) {
                if (err instanceof JPush.APIConnectionError) {
                    console.log(err.message);
                    //Response Timeout means your request to the server may have already received, please check whether or not to push
                    console.log(err.isResponseTimeout);
                } else if (err instanceof  JPush.APIRequestError) {
                    console.log(err.message);
                }
            } else {
                if(!overrideMsgId) msgIdArray[alias] = res.msg_id;
                console.log('Sendno: ' + res.sendno);
                console.log('Msg_id: ' + res.msg_id);
            }
        });

    },
    MD5: function(value) { //md5 加密
        return cryptojs.MD5((value || "") + Consts.SECRETKEY);
    },
    mailSend: function(to, subject, text, html, cb) {
        var nodemailer = require("nodemailer");
        var transporte = nodemailer.createTransport("SMTP", {
            server: "QQex",
            host: "smtp.exmail.qq.com", // 主机
            secureConnection: true, // 使用 SSL
            port: 465, // SMTP 端口
            auth: {
                user: "bochy_pingtai@bochy.com.cn",
                pass: "bochyadmin01"
            }
        });

        var opcionesMail = {
            from: "bochy_pingtai@bochy.com.cn",
            to: to,
            subject: subject,
            text: text,
            html: html
        };
        transporte.sendMail(opcionesMail, function(error, response) {
            cb(error, response);
        });
    },
    //创建6位随机数（0-9范围内）
    random: function() {
        var items = '0123456789'.split('');
        var vcode = '';
        for (var i = 0; i < 6; i++) {
            var rnd = Math.random();
            var item = Math.round(rnd * (items.length - 1));
            vcode += items[item];
        }
        return vcode;
    },
    //拼音首字母
    py: function(s) {
        if (!s || s == "")
            return '';
        var result = pinyin(s, {
            style: pinyin.STYLE_FIRST_LETTER,
            heteronym: false
        });
        return result[0][0];
    },

    //上传文件
    //rotation:是否旋转图片; updatephoto:更新头像调用该参数，会把图片转成正方形图
    //compress:是否后台压缩图片
    upload: function(req, cb) {
        console.log("utils/upload");
        var form = new multiparty.Form();
        form.parse(req, function(err, fields, files) {
            if (err || (!files.file[0])) 
                return cb(resultJson(500));

            var rotation = req.query.rotation || 0;
            var updatephoto = req.query.updatephoto;
            var compress = req.query.compress;
            console.log("upload rotation-->" + rotation);
            console.log("upload updatephoto-->" + util.inspect(updatephoto));
            console.log("upload compress-->" + compress);

            var tmp_path = files.file[0].path;
            var filename = files.file[0].originalFilename;
            var ext = Utils.getExt(filename).toString().toLowerCase();
            console.log("ext:" + ext);
            if (ext == "") {
                console.log("ext is empty, donot upload it");
                return cb(resultJson(550));
            }
            var size = files.file[0].size;
            var uid = uuid.v1();
            var target_file = uid + ext;
            console.log("target_file:" + target_file);
            //create 'upload/image' if it doesn't exist
            mkdirp.sync(setting.upload);

            var target_path = setting.upload + target_file;
            console.log("upload, target path=" + target_path);
            if (ext != ".jpeg" && ext != ".jpg" && ext != ".png") {
                var is = fs.createReadStream(tmp_path);
                var os = fs.createWriteStream(target_path);
                is.pipe(os);
                is.on('end', function() {
                    Utils.uploadFinish(filename, target_file, size, tmp_path, cb);
                });
                return;
            }

            //后台压缩上传的图片
            if (compress == 1) {
                gm(tmp_path).resize(640).noProfile().write(target_path, function(err) {
                    if (err)
                        console.log('gm resize error:' + err);
    
                    var thumbnail = target_path.substring(0, target_path.lastIndexOf(".")) + "_thumbnail" + target_path.substring(target_path.lastIndexOf("."));
                    console.log('thumbnail=' + thumbnail);
                    gm(tmp_path).resize(160).noProfile().write(thumbnail, function(err) {
                        return Utils.uploadFinish(filename, target_file, size, tmp_path, cb);
                    });
                });
            } else {
                var thumbnail = target_path.substring(0, target_path.lastIndexOf(".")) + "_thumbnail" + target_path.substring(target_path.lastIndexOf("."));
                console.log('thumbnail=' + thumbnail);
                gm(tmp_path).resize(160).noProfile().write(thumbnail, function(err) {
                    var is = fs.createReadStream(tmp_path);
                    var os = fs.createWriteStream(target_path);
                    is.pipe(os);
                    is.on('end', function() {
                        if (updatephoto == true) {
                            gm(target_path).size(function(err, size) {
                                if (err) {
                                    console.log('gm resize picture error');
                                    return Utils.uploadFinish(filename, target_file, size, tmp_path, cb);
                                }
                                var x = y = 0;
                                var width;
                                if (size.width > size.height) {
                                    x = (size.width - size.height) / 2;
                                    width = size.height;
                                } else {
                                    y = (size.height - size.width) / 2;
                                    width = size.width;
                                }
                                console.log("x:" + x + " y:" + y + " width:" + width);
                                gm(target_path).crop(width, width, x, y).noProfile().write(target_path, function(err) {
                                    console.log("err:" + err);
                                    Utils.uploadFinish(filename, target_file, size, tmp_path, cb);
                                });
                            });
                        } else {
                            Utils.uploadFinish(filename, target_file, size, tmp_path, cb);
                        }
                    });
                });
            }
        })
    },

    uploadFinish: function(filename, url, size, tmp_path, cb) {
        fs.unlink(tmp_path, function(err) {
            if (err)
                console.log("rm " + tmp_path + " failed");
        });

        cb(resultJson(0, {
            filename: filename,
            url: url,
            size: size
        }));
    },

    //删除文件
    delete: function(url) {
        if (!url)
            return;
        var file = setting.upload + url;
        console.log(file);
        fs.unlink(file, function(err) {
            if (err)
                console.log("rm " + file + " failed");
        });
    },

    getExt: function(filename) {
        if (!filename)
            return;
        return /\.[^\.]+$/.exec(filename);
    },

    getDayCount: function(year, month) {
        var count = 0;
        if (month == 2) {
            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
                count = 29;
            else
                count = 28;
        } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
            count = 31;
        else if (month == 4 || month == 6 || month == 9 || month == 11)
            count = 30;
        return count;
    },
    fanyi: function(from, to, content, cb) {
        //var con = iconv.decode(content,'UTF8');
       // var buf = new Buffer(content,'utf8');
        //var con = iconv.decode(buf,'gbk');
        //var con1 = buf.toString('utf8',0,buf.length);
        //console.log(buf);
       // console.log(buf.toString('utf8',0,buf.length));
        //console.log(con);
        //console.log("CON:"+con);
        var url = "http://fanyi.baidu.com/v2transapi?from="+from+"&to="+to+"&query="+content;
        
       // var url = "http://123.57.212.18/day10_3/cp?query="+content;
        console.log("url:"+url);
        
        http.get(url, function(res) { 
            console.log('STATUS: ' + res.statusCode);  
            console.log('HEADERS: ' + JSON.stringify(res.headers));
            var result = '';            
            res.setEncoding('utf8');
            res.on('data', function(data) {
                result += data;
            });
            res.on('end', function() {
                var obj = JSON.parse(result),
                str = obj.trans_result.data[0].dst;
                cb(str);
                
            });
        }).on('error', function(e) { 
            console.log("Got error: " + e.message); 
            cb("");
        });     
       

        
    },
    yanzhengma: function(phone,msg,cb) {
        var url = "http://127.0.0.1:8080/ecsms/send?phone="+phone+"&msg="+msg
        console.log("url:"+url);
        http.get(url, function(res) { 
            console.log('STATUS: ' + res.statusCode);  
            console.log('HEADERS: ' + JSON.stringify(res.headers));
            var result = '';            
            res.setEncoding('utf8');
            res.on('data', function(data) {
                result += data;
            });
            res.on('end', function() {
                console.log(result);
                var obj = JSON.parse(result),
                str = obj.result;
                cb(result);
            });
        }).on('error', function(e) { 
            console.log("Got error: " + e.message); 
            cb("");
        });     
    }
};

/** * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
    可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
    Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423      
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04      
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04      
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04      
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */

Date.prototype.pattern = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时 (12小时制)
        "H+": this.getHours(), //小时 (24小时制)
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
Array.prototype.find = function(val, key) {
    if (key) {
        for (var i = 0; i < this.length; ++i) {
            if (this[i][key] == val)
                return i;
        }
    } else {
        for (var i = 0; i < this.length; ++i) {
            if (this[i] == val)
                return i;
        }
    }
    return -1;
}
module.exports = Utils;